#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2025   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：DESKTOP-GLJ2Q8J
 * 公司名称：
 * 命名空间：AutoCAD.EntityTools.Ribbon
 * 唯一标识：00bd6f84-cfbf-4cfa-9dd4-e1760a7553f8
 * 文件名：RibbonBuilderBase
 * 当前用户域：DESKTOP-GLJ2Q8J
 * 
 * 创建者： Guo_79991
 * 电子邮箱：xxxx@hotmail.com
 * 创建时间：2025/8/30 22:44:15
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>




namespace AutoCAD.EntityTools.Ribbon
{
    ///// <summary>
    ///// RibbonBuilderBase 的摘要说明
    ///// </summary>
    ///// <summary>
    ///// 可继承的Ribbon UI构建基类
    ///// </summary>
    //public abstract class RibbonBuilderBase
    //{
    //    protected string _tabId = "_DefaultTab";
    //    protected string _tabTitle = "默认功能区";
    //    protected string _configXmlPath;
    //    protected string _iconsBasePath;
    //    protected RibbonCommand _ribbonCommand;

    //    // 面板配置
    //    protected List<PanelConfig> _panelConfigs = new List<PanelConfig>();

    //    /// <summary>
    //    /// 默认构造函数
    //    /// 
    //    /// </summary>
    //    protected RibbonBuilderBase()
    //    {

    //        /*
    //         * <?xml version="1.0" encoding="utf-8" ?>
    //            <config>
    //                <Tab name="测试Ribbon" isActive="true">
    //                    <Panel name="墙线处理插件">
    //                        <Button name="测试" command="TestCommand" title="测试" content="只是测试按钮"  
    //                        expandcontent="附加内容  \n  详细内容" expandimgName="ccadtest.jpg"  imagePath="test" isShow = "false"/>
    //                        <Button name="特性面板" command="PaletteCommand" title="特性面板页面" content="停靠面板按钮" 
    //                        expandcontent="设置、配置 \n  关于日志" expandimgName="特性.jpg" imagePath="palette" isShow = "false"/>
    //                        <Button name="授权窗口" command="AuthorizationCommand" itle="授权功能" content="授权功能检查是否有权限"  
    //                        expandcontent="先获取机器码  \n  输入授权码激活    \n  无权限则退出插件" expandimgName="cadbig.jpeg" imagePath="授权" isShow = "true"/>
    //                        <Button name="设置" command="ConfigManageWindowCommand"  title="设置配置" content="设置配置功能"  
    //                        expandcontent="1、设置允许距离  \n  2、中线要设置的图层  \n  3、自动筛选的图层名  \n  4、车位线图层  \n  5、要导出的图框图层  \n  6、保存文件路径  \n  7、全局误差值  \n  8、门窗距离特征  " expandimgName="配置Tooltip.png" imagePath="ConfigManage" isShow = "true" />
    //                                    <Button name="定位当前文件" command="OpenFileLocationCommand" title="定位当前图所在位置测试" 
    //                        content="定位当前图所在位置功能"  
    //                        expandcontent="打开本地图形所在位置" expandimgName="开发中.jpg"  imagePath="定位" isShow = "true"/>
    //                        <RowAddItems name="保存" command="SaveEachLayerDwgCommand" title="根据图框保存" content="根据图框保存功能"  
    //                        expandcontent="根据图框保存图框中的过滤实体以及中线生成  \n  确保已配置导出图框图层" expandimgName="保存ToopTip.png" imagePath="Save" isShow = "true"/>
    //                         <RowAddItems name="关闭其他" command="YCQTCommand"  title="关闭其他图层" content="关闭其他图层功能"  
    //                        expandcontent="选择要显示（孤立）的实体  \n   只显示所选实体图层" expandimgName="关闭其他ToolTip.png" imagePath="隐藏其他片区" isShow = "true"/>
    //                        <RowAddItems name="显示所有" command="XSQBCommand" title="显示所有隐藏的图层" content="显示所有隐藏的图层功能"  
    //                        expandcontent="把所有隐藏的图层显示出来..." expandimgName="显示所有ToolTip.png" imagePath="显示所有" isShow = "true"/>
    //                        <RowAddItems name="关于我们" command="AboutUsCommand" title="关于我们" content="关于我们功能"  
    //                        expandcontent="关于我们  \n  这里是一豪工作室  \n  https://blog.csdn.net/ultramand" 
    //                        expandimgName="call_9a279b38-e6b8-11ef-8b95-9e2d06b09a34_0.png"  imagePath="关于" isShow = "true"/>


    //                        <SplitButton name="墙中线" command="CreateTest" imagePath="墙中线" isShow = "false"/>
    //                        <ComboButton name="复杂测试" command="CreatePrimitives" imagePath="ent" isShow = "false"/>
    //                    </Panel>
    //                </Tab>
    //            </config>
    //         */








    //        // 设置默认值
    //        _configXmlPath = Path.Combine(ConfigPath._ProfilePath2, "AcadConfig.xml");
    //        _iconsBasePath = ConfigPath.AssemblyRunRootPath;

    //        // 默认面板配置
    //        _panelConfigs.Add(new PanelConfig { Title = "配置工具" });
    //        _panelConfigs.Add(new PanelConfig { Title = "生成工具" });
    //    }

    //    /// <summary>
    //    /// 创建Ribbon界面
    //    /// </summary>
    //    public virtual bool CreateRibbon()
    //    {
    //        try
    //        {
    //            var ribbonTab = new RibbonTab()
    //            {
    //                Id = _tabId,
    //                Title = _tabTitle,
    //                IsActive = true
    //            };

    //            // 创建面板
    //            foreach (var panelConfig in _panelConfigs)
    //            {
    //                var ribbonPanelSource = new RibbonPanelSource()
    //                {
    //                    Title = panelConfig.Title
    //                };

    //                var ribbonPanel = new RibbonPanel() { Source = ribbonPanelSource };

    //                // 添加按钮到面板
    //                AddButtonsToPanel(ribbonPanelSource, panelConfig);

    //                ribbonTab.Panels.Add(ribbonPanel);
    //            }

    //            ComponentManager.Ribbon.Tabs.Add(ribbonTab);
    //            return true;
    //        }
    //        catch (System.Exception ex)
    //        {
    //            HandleUIError(ex);
    //            return false;
    //        }
    //    }

    //    /// <summary>
    //    /// 添加按钮到面板
    //    /// </summary>
    //    protected virtual void AddButtonsToPanel(RibbonPanelSource panelSource, PanelConfig panelConfig)
    //    {
    //        var buttons = CreateButtonsCommand(Orientation.Vertical);

    //        foreach (var button in buttons.Buttons)
    //        {
    //            panelSource.Items.Add(button);
    //        }

    //        foreach (var button in buttons.SplitButtons)
    //        {
    //            panelSource.Items.Add(button);
    //        }

    //        foreach (var button in buttons.ComboButtons)
    //        {
    //            panelSource.Items.Add(button);
    //        }

    //        foreach (var button in buttons.RowPanels)
    //        {
    //            panelSource.Items.Add(button);
    //        }
    //    }
    //    /// <summary>
    //    /// 按钮命令结果结构体
    //    /// </summary>
    //    public struct ButtonCommandResult
    //    {
    //        public List<RibbonButton> Buttons;
    //        public List<RibbonSplitButton> SplitButtons;
    //        public List<RibbonCombo> ComboButtons;
    //        public List<RibbonRowPanel> RowPanels;
    //    }

    //    /// <summary>
    //    /// 创建按钮命令
    //    /// </summary>
    //    protected virtual ButtonCommandResult CreateButtonsCommand(Orientation orientation)
    //    {
    //        var result = new ButtonCommandResult
    //        {
    //            Buttons = new List<RibbonButton>(),
    //            SplitButtons = new List<RibbonSplitButton>(),
    //            ComboButtons = new List<RibbonCombo>(),
    //            RowPanels = new List<RibbonRowPanel>()
    //        };

    //        try
    //        {
    //            if (!File.Exists(_configXmlPath))
    //            {
    //                $"配置文件不存在: {_configXmlPath}".CadMessage2();
    //                return result;
    //            }

    //            XmlDocument xmlDoc = new XmlDocument();
    //            xmlDoc.Load(_configXmlPath);

    //            XmlNodeList buttonNodes = xmlDoc.SelectNodes("//Tab/Panel/*");

    //            foreach (XmlNode buttonNode in buttonNodes)
    //            {
    //                ProcessButtonNode(buttonNode, orientation, result.Buttons, result.SplitButtons,
    //                    result.ComboButtons, result.RowPanels);
    //            }
    //        }
    //        catch (System.Exception ex)
    //        {
    //            ($"创建按钮时出错: {ex.Message}").CadMessage2();
    //        }

    //        return result;
    //    }



    //    /// <summary>
    //    /// 处理按钮节点
    //    /// </summary>
    //    protected virtual void ProcessButtonNode(XmlNode buttonNode, Orientation orientation,
    //        List<RibbonButton> buttons, List<RibbonSplitButton> splitButtons,
    //        List<RibbonCombo> comboButtons, List<RibbonRowPanel> rowPanels)
    //    {
    //        string label = buttonNode.Attributes["name"]?.Value;
    //        string img = buttonNode.Attributes["imagePath"]?.Value;
    //        string commandName = buttonNode.Attributes["command"]?.Value;
    //        string isShow = buttonNode.Attributes["isShow"]?.Value;

    //        if (!bool.TryParse(isShow, out bool isVisible) || !isVisible)
    //            return;

    //        ICommand command = GetCommand(commandName);

    //        switch (buttonNode.Name)
    //        {
    //            case "Button":
    //                CreateButton(command, label, img, out RibbonButton button, orientation);
    //                buttons.Add(button);
    //                break;

    //            case "SplitButton":
    //                CreateSplitButton(out RibbonSplitButton splitButton, img, command, label, orientation);
    //                splitButtons.Add(splitButton);
    //                break;

    //            case "ComboButton":
    //                CreateComboButton(img, label, command, out RibbonCombo comboButton, orientation);
    //                comboButtons.Add(comboButton);
    //                break;

    //            case "RowAddItems":
    //                CreateRowButton(label, img, command, out RibbonRowPanel rowPanel, orientation);
    //                rowPanels.Add(rowPanel);
    //                break;
    //        }
    //    }

    //    /// <summary>
    //    /// 获取命令（可重写）
    //    /// </summary>WallProcessingRibbonBuilder 
    //    protected virtual ICommand GetCommand(string commandName)
    //    {
    //        if (_ribbonCommand == null)
    //            return null;

    //        // 使用反射动态获取命令属性
    //        var property = _ribbonCommand.GetType().GetProperty(commandName);
    //        if (property != null && property.PropertyType == typeof(ICommand))
    //        {
    //            return (ICommand)property.GetValue(_ribbonCommand);
    //        }

    //        return null;
    //    }

    //    /// <summary>
    //    /// 创建按钮（可重写）
    //    /// </summary>
    //    protected virtual void CreateButton(ICommand command, string text, string image, out RibbonButton button,
    //        Orientation orientation = Orientation.Horizontal)
    //    {
    //        var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{image}32.png");
    //        var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{image}16.png");

    //        button = new RibbonButton()
    //        {
    //            ShowText = true,
    //            Text = text,
    //            Size = RibbonItemSize.Large,
    //            ShowImage = true,
    //            LargeImage = LoadImage(imagePath32),
    //            Image = LoadImage(imagePath16),
    //            CommandHandler = command,
    //            Orientation = orientation
    //        };
    //    }

    //    /// <summary>
    //    /// 创建分割按钮（可重写）
    //    /// </summary>
    //    protected virtual void CreateSplitButton(out RibbonSplitButton splitButton, string imageName,
    //        ICommand command, string text, Orientation orientation)
    //    {
    //        var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{imageName}32.png");
    //        var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{imageName}16.png");

    //        splitButton = new RibbonSplitButton()
    //        {
    //            ShowText = true,
    //            Text = text,
    //            Size = RibbonItemSize.Large,
    //            ShowImage = true,
    //            LargeImage = LoadImage(imagePath32),
    //            Image = LoadImage(imagePath16),
    //            CommandHandler = command,
    //            Orientation = orientation
    //        };
    //    }
    //    public abstract class RibbonCommand
    //    {
    //        /// <summary>
    //        /// 获取命令的方法（抽象方法，子类必须实现）
    //        /// </summary>
    //        public abstract ICommand GetCommand(string commandName);

    //        /// <summary>
    //        /// 发送命令到CAD
    //        /// </summary>
    //        protected void SendCommand(string command)
    //            => Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
    //               .SendStringToExecute($"{command} ", true, false, false);
    //    }
    //    /// <summary>
    //    /// 创建组合按钮（可重写）
    //    /// </summary>
    //    protected virtual void CreateComboButton(string imageName, string text, ICommand command,
    //        out RibbonCombo comboButton, Orientation orientation)
    //    {
    //        var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{imageName}32.png");
    //        var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{imageName}16.png");

    //        comboButton = new RibbonCombo()
    //        {
    //            ShowText = true,
    //            Text = text,
    //            Size = RibbonItemSize.Standard,
    //            ShowImage = true,
    //            LargeImage = LoadImage(imagePath32),
    //            Image = LoadImage(imagePath16),
    //            CommandHandler = command
    //        };
    //    }

    //    /// <summary>
    //    /// 创建行按钮（可重写）
    //    /// </summary>
    //    protected virtual void CreateRowButton(string text, string imageName, ICommand command,
    //        out RibbonRowPanel rowPanel, Orientation orientation)
    //    {
    //        var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{imageName}32.png");
    //        var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{imageName}16.png");

    //        rowPanel = new RibbonRowPanel()
    //        {
    //            ShowText = true,
    //            Text = text,
    //            Size = RibbonItemSize.Large,
    //            ShowImage = true,
    //            LargeImage = LoadImage(imagePath32),
    //            Image = LoadImage(imagePath16),
    //            SubPanelResizeStyle = RibbonRowPanelResizeStyle.NoResize,
    //            Height = 40
    //        };
    //    }

    //    /// <summary>
    //    /// 加载图片
    //    /// </summary>
    //    protected virtual System.Windows.Media.ImageSource LoadImage(string imagePath)
    //    {
    //        if (File.Exists(imagePath))
    //        {
    //            return ImageHelper.FileToBitmap(imagePath);
    //        }

    //        // 返回默认图片
    //        return GetDefaultImage(32);
    //    }

    //    /// <summary>
    //    /// 获取默认图片
    //    /// </summary>
    //    protected virtual System.Windows.Media.ImageSource GetDefaultImage(int size)
    //    {
    //        var visual = new System.Windows.Media.DrawingVisual();
    //        using (var context = visual.RenderOpen())
    //        {
    //            context.DrawRectangle(
    //                System.Windows.Media.Brushes.LightGray,
    //                new System.Windows.Media.Pen(System.Windows.Media.Brushes.DarkGray, 1),
    //                new System.Windows.Rect(0, 0, size, size));
    //        }

    //        var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap(
    //            size, size, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
    //        bitmap.Render(visual);

    //        return bitmap;
    //    }

    //    /// <summary>
    //    /// 处理UI错误
    //    /// </summary>
    //    protected virtual void HandleUIError(System.Exception ex)
    //    {
    //        ($"UI创建错误: {ex.Message}").CadMessage2();
    //        ex.StackTrace.CadAlert();
    //    }
    //}

    ///// <summary>
    ///// 面板配置类
    ///// </summary>
    //public class PanelConfig
    //{
    //    public string Title { get; set; }
    //    public Orientation Orientation { get; set; } = Orientation.Vertical;
    //}
    ///// <summary>
    ///// CAD扩展应用程序的抽象基类
    ///// </summary>
    //public abstract class AppStartBase : IExtensionApplication
    //{
    //    protected RibbonBuilderBase _ribbonBuilder;

    //    /// <summary>
    //    /// 初始化应用程序
    //    /// </summary>
    //    public virtual void Initialize()
    //    {
    //        try
    //        {
    //            "------------程序开始初始化------------".CadMessage2();

    //            // 加载依赖DLL
    //            LoadDependencies();

    //            RegisterService();
    //            ComponentManager.ItemInitialized += ComponentManager_ItemInitialized;

    //            AppDomain.CurrentDomain.AssemblyLoad += (sender, args) =>
    //            {
    //                $"已加载程序集: {args.LoadedAssembly.FullName}".CadMessage2();
    //            };
    //        }
    //        catch (System.Exception ex)
    //        {
    //            HandleError("初始化失败", ex);
    //        }
    //    }

    //    /// <summary>
    //    /// 加载依赖项（可重写）
    //    /// </summary>
    //    protected virtual void LoadDependencies()
    //    {
    //        var dllPath = ConfigPath.Dllfloder + "\\HandyControl.dll";
    //        if (!File.Exists(dllPath))
    //        {
    //            $"未加载到dll，没有找到文件 ---{dllPath} ---".CadMessage2();
    //            return;
    //        }

    //        Assembly.LoadFrom(dllPath);
    //        $"加载到dll ---{dllPath} ---".CadMessage2();
    //    }

    //    private void ComponentManager_ItemInitialized(object sender, RibbonItemEventArgs e)
    //    {
    //        if (ComponentManager.Ribbon != null)
    //        {
    //            LoadUI();
    //        }
    //        Autodesk.Windows.ComponentManager.ItemInitialized -= ComponentManager_ItemInitialized;
    //    }

    //    /// <summary>
    //    /// 加载UI界面（抽象方法，子类必须实现）
    //    /// </summary>
    //    protected abstract void LoadUI();

    //    /// <summary>
    //    /// 创建Ribbon构建器（可重写）
    //    /// </summary>
    //    protected virtual RibbonBuilderBase CreateRibbonBuilder()
    //    {
    //        return null;
    //    }

    //    /// <summary>
    //    /// 错误处理（可重写）
    //    /// </summary>
    //    protected virtual void HandleError(string context, System.Exception ex)
    //    {
    //        Application.ShowAlertDialog($"{context}: {ex.Message}");
    //        ex.Message.CadMessage2();
    //        ex.StackTrace.CadMessage2();
    //        ("引发异常的方法:" + ex.TargetSite).CadMessage2();
    //        ("导致异常的应用程序或对象的名称:" + ex.Source).CadMessage2();
    //        ("导致当前异常的 Exception 实例:" + ex.InnerException).CadMessage2();
    //    }

    //    /// <summary>
    //    /// 注册服务（可重写）
    //    /// </summary>
    //    protected virtual void RegisterService()
    //    {
    //        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
    //    }

    //    /// <summary>
    //    /// 程序集解析（可重写）
    //    /// </summary>
    //    protected virtual Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    //    {
    //        try
    //        {
    //            AssemblyName assemblyName = new AssemblyName(args.Name);
    //            string[] possibleExtensions = new[] { ".dll", ".exe" };

    //            // 检查插件目录
    //            string pluginPath = Path.Combine(ConfigPath.AssemblyRunRootPath, "Plugins");
    //            foreach (var ext in possibleExtensions)
    //            {
    //                string filePath = Path.Combine(pluginPath, $"{assemblyName.Name}{ext}");
    //                if (File.Exists(filePath))
    //                {
    //                    return Assembly.LoadFrom(filePath);
    //                }
    //            }

    //            // 检查主目录
    //            foreach (var ext in possibleExtensions)
    //            {
    //                string filePath = Path.Combine(ConfigPath.AssemblyRunRootPath, $"{assemblyName.Name}{ext}");
    //                if (File.Exists(filePath))
    //                {
    //                    return Assembly.LoadFrom(filePath);
    //                }
    //            }

    //            $"未能解析程序集: {args.Name}".CadMessage2();
    //        }
    //        catch (System.Exception ex)
    //        {
    //            $"程序集解析失败: {ex.Message}".CadMessage2();
    //        }
    //        return null;
    //    }

    //    /// <summary>
    //    /// 终止应用程序
    //    /// </summary>
    //    public virtual void Terminate()
    //    {
    //        // 清理资源
    //        "------------程序结束运行------------".CadMessage2();
    //    }
    //}




































































    /// <summary>
    /// 面板配置类
    /// </summary>
    public class PanelConfig
    {
        public string Title { get; set; }
        public Orientation Orientation { get; set; } = Orientation.Vertical;
    }

    /// <summary>
    /// Ribbon命令抽象基类
    /// </summary>
    public abstract class RibbonCommand
    {
        /// <summary>
        /// 获取命令的方法（抽象方法，子类必须实现）
        /// </summary>
        public abstract ICommand GetCommand(string commandName);

        /// <summary>
        /// 发送命令到CAD
        /// </summary>
        protected void SendCommand(string command)
            => Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
               .SendStringToExecute($"{command} ", true, false, false);
    }

    /// <summary>
    /// 可继承的Ribbon UI构建基类
    /// </summary>
    public abstract class RibbonBuilderBase
    {
        protected string _tabId = "_DefaultTab";
        protected string _tabTitle = "默认功能区";
        protected string _configXmlPath;
        protected string _iconsBasePath;
        protected RibbonCommand _ribbonCommand;

        // 面板配置
        protected List<PanelConfig> _panelConfigs = new List<PanelConfig>();

        /// <summary>
        /// 默认构造函数
        /// </summary>
        protected RibbonBuilderBase()
        {
            InitializeDefaults();
        }

        /// <summary>
        /// 初始化默认配置（可重写）
        /// </summary>
        protected virtual void InitializeDefaults()
        {
            // 设置默认值
            _configXmlPath = Path.Combine(ConfigPath._ProfilePath2, "AcadConfig.xml");
            _iconsBasePath = ConfigPath.AssemblyRunRootPath;

            // 默认面板配置
            _panelConfigs.Add(new PanelConfig { Title = "配置工具" });
            _panelConfigs.Add(new PanelConfig { Title = "生成工具" });
        }

        /// <summary>
        /// 创建Ribbon界面
        /// </summary>
        public virtual bool CreateRibbon()
        {
            try
            {
                var ribbonTab = new RibbonTab()
                {
                    Id = _tabId,
                    Title = _tabTitle,

                };
                //var ribbonTab = new RibbonTab()
                //{
                //    Id = _tabId,
                //    Title = _tabTitle,
                //    IsActive = true
                //};
                // 创建面板
                foreach (var panelConfig in _panelConfigs)
                {
                    var ribbonPanelSource = new RibbonPanelSource() { Title = panelConfig.Title };
                    var ribbonPanel = new RibbonPanel() { Source = ribbonPanelSource };

                    // 添加按钮到面板
                    AddButtonsToPanel(ribbonPanelSource, panelConfig);
                    ribbonTab.Panels.Add(ribbonPanel);
                    // 激活并刷新选项卡显示
                    //RibbonRefreshHelper.ActivateTab(_tabId);
                }

                ComponentManager.Ribbon.Tabs.Add(ribbonTab);
                return ribbonTab.IsActive = true;
                //return true;
            }
            catch (System.Exception ex)
            {
                HandleUIError(ex);
                return false;
            }
        }

        /// <summary>
        /// 添加按钮到面板
        /// </summary>
        protected virtual void AddButtonsToPanel(RibbonPanelSource panelSource, PanelConfig panelConfig)
        {
            var buttons = CreateButtonsCommand(Orientation.Vertical);

            foreach (var button in buttons.Buttons)
            {
                panelSource.Items.Add(button);
            }

            foreach (var button in buttons.SplitButtons)
            {
                panelSource.Items.Add(button);
            }

            foreach (var button in buttons.ComboButtons)
            {
                panelSource.Items.Add(button);
            }

            foreach (var button in buttons.RowPanels)
            {
                panelSource.Items.Add(button);
            }
        }

        /// <summary>
        /// 按钮命令结果结构体
        /// </summary>
        public struct ButtonCommandResult
        {
            public List<RibbonButton> Buttons;
            public List<RibbonSplitButton> SplitButtons;
            public List<RibbonCombo> ComboButtons;
            public List<RibbonRowPanel> RowPanels;
        }

        /// <summary>
        /// 创建按钮命令
        /// </summary>
        protected virtual ButtonCommandResult CreateButtonsCommand(Orientation orientation)
        {
            var result = new ButtonCommandResult
            {
                Buttons = new List<RibbonButton>(),
                SplitButtons = new List<RibbonSplitButton>(),
                ComboButtons = new List<RibbonCombo>(),
                RowPanels = new List<RibbonRowPanel>()
            };

            try
            {
                if (!File.Exists(_configXmlPath))
                {
                    $"配置文件不存在: {_configXmlPath}".CadMessage2();
                    return result;
                }

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(_configXmlPath);

                XmlNodeList buttonNodes = xmlDoc.SelectNodes("//Tab/Panel/*");

                foreach (XmlNode buttonNode in buttonNodes)
                {
                    ProcessButtonNode(buttonNode, orientation, result.Buttons, result.SplitButtons,
                        result.ComboButtons, result.RowPanels);
                }
            }
            catch (System.Exception ex)
            {
                ($"创建按钮时出错: {ex.Message}").CadMessage2();
            }

            return result;
        }

        /// <summary>
        /// 处理按钮节点
        /// </summary>
        protected virtual void ProcessButtonNode(XmlNode buttonNode, Orientation orientation,
            List<RibbonButton> buttons, List<RibbonSplitButton> splitButtons,
            List<RibbonCombo> comboButtons, List<RibbonRowPanel> rowPanels)
        {
            string label = buttonNode.Attributes["name"]?.Value;
            string img = buttonNode.Attributes["imagePath"]?.Value;
            string commandName = buttonNode.Attributes["command"]?.Value;
            string isShow = buttonNode.Attributes["isShow"]?.Value;
            var expandimgName = buttonNode.Attributes["expandimgName"]?.Value;
            var expandcontent = buttonNode.Attributes["expandcontent"]?.Value;
            string title = buttonNode.Attributes["title"]?.Value;
            string content = buttonNode.Attributes["content"]?.Value;
            if (!bool.TryParse(isShow, out bool isVisible) || !isVisible)
                return;
            if (expandimgName is "")
            {
                expandimgName = "开发中.jpg";
            }

            if (expandcontent != null)
            {
                expandcontent = expandcontent.ProcessNewLines();
            }
            var expandimgPath = Path.Combine(ConfigPath.AssemblyRunRootPath, "icons", $"{expandimgName}");
            ICommand command = GetCommand(commandName);
            var currentCommand = GetCommand(commandName, _ribbonCommand);
            switch (buttonNode.Name)
            {
                case "Button":
                    CreateButton(currentCommand, label, img, out RibbonButton button,  expandimgPath , commandName , 
                        title , content , expandcontent, orientation);
                    buttons.Add(button);
                    break;

                case "SplitButton":
                    CreateSplitButton(out RibbonSplitButton splitButton, img, currentCommand, label, orientation
                        , expandimgPath, commandName,
                        title, content, expandcontent);
                    splitButtons.Add(splitButton);
                    break;

                case "ComboButton":
                    CreateComboButton(img, label, currentCommand, out RibbonCombo comboButton,
                        orientation, expandimgPath, commandName,
                        title, content, expandcontent);
                    comboButtons.Add(comboButton);
                    break;

                case "RowAddItems":
                    CreateRowButton(label, img, currentCommand, out RibbonRowPanel rowPanel, 
                        orientation, expandimgPath, commandName,
                        title, content, expandcontent);
                    rowPanels.Add(rowPanel);
                    break;
            }
        }

        /// <summary>
        /// 获取命令（可重写）
        /// </summary>
        protected virtual ICommand GetCommand(string commandName)
        {
            if (_ribbonCommand == null)
                return null;

            // 使用反射动态获取命令属性
            var property = _ribbonCommand.GetType().GetProperty(commandName);
            if (property != null && property.PropertyType == typeof(ICommand))
            {
                return (ICommand)property.GetValue(_ribbonCommand);
            }

            return null;
        }

        private static ICommand GetCommand(string commandName, RibbonCommand ribbonCommand)
        {
            if (ribbonCommand == null)
                return null;

            // 使用反射获取属性
            var property = ribbonCommand.GetType().GetProperty(commandName);
            if (property != null)
            {
                return (ICommand)property.GetValue(ribbonCommand);
            }

            return null;
        }


        //private static ICommand GetCommand(string commandName, RibbonCommand ribbonCommand)
        //{
        //    if (ribbonCommand == null)
        //        return null;

        //    // 智能选择：优先实例方法，失败则使用反射
        //    try
        //    {
        //        // 尝试调用重写的GetCommand方法
        //        return ribbonCommand.GetCommand(commandName);
        //    }
        //    catch
        //    {
        //        // 如果重写的方法不存在或出错，使用反射作为备用
        //        var property = ribbonCommand.GetType().GetProperty(commandName);
        //        if (property?.PropertyType == typeof(ICommand))
        //        {
        //            return (ICommand)property.GetValue(ribbonCommand);
        //        }
        //        return null;
        //    }
        //}

        /// <summary>
        /// 创建按钮（可重写）
        /// </summary>
        protected virtual void CreateButton(ICommand command, string text, string image, out RibbonButton button,
          string expandimgPath  ,  string commandName , string title ,
          string content, string expandcontent,  Orientation orientation = Orientation.Horizontal)
        {
            var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{image}32.png");
            var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{image}16.png");

            RibbonToolTip toolTipLine = new RibbonToolTip();//创建按钮提示
            toolTipLine.Command = commandName;//设置提示中显示的命令名
            toolTipLine.Title = title;//设置提示的标题
            toolTipLine.Content = content;//设置提示的内容
            //设置提示的附加内容
            toolTipLine.ExpandedContent = expandcontent;
            //设置在提示附加内容下显示的图像
            toolTipLine.ExpandedImage = File.Exists(expandimgPath) ? ImageHelper.FileToBitmap(expandimgPath) : GetDefaultImage(16);



            button = new RibbonButton()
            {
                ShowText = true,
                Text = text,
                Size = RibbonItemSize.Large,
                ShowImage = true,
                LargeImage = LoadImage(imagePath32),
                Image = LoadImage(imagePath16),
                CommandHandler = command,
                Orientation = orientation,
                ToolTip = toolTipLine,
                Description = string.IsNullOrEmpty(text) ? "功能命令" : $"{text} 相关命令",
                HelpSource = new Uri(expandimgPath),
                // 交互效果
                IsEnabled = true,
                //ShowImage = true,
                // 尺寸样式
                Height = 6,  // 更合适的高度
                MinWidth = 20,

            };
        }

        /// <summary>
        /// 创建分割按钮（可重写）
        /// </summary>
        protected virtual void CreateSplitButton(out RibbonSplitButton splitButton, string imageName,
            ICommand command, string text, Orientation orientation ,
             string expandimgPath, string commandName, string title,
          string content, string expandcontent)
        {
            var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{imageName}32.png");
            var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{imageName}16.png");



            RibbonToolTip toolTipLine = new RibbonToolTip();//创建按钮提示
            toolTipLine.Command = commandName;//设置提示中显示的命令名
            toolTipLine.Title = title;//设置提示的标题
            toolTipLine.Content = content;//设置提示的内容
            //设置提示的附加内容
            toolTipLine.ExpandedContent = expandcontent;
            //设置在提示附加内容下显示的图像
            toolTipLine.ExpandedImage = File.Exists(expandimgPath) ? ImageHelper.FileToBitmap(expandimgPath) : GetDefaultImage(16);





            splitButton = new RibbonSplitButton()
            {
                ShowText = true,
                Text = text,
                Size = RibbonItemSize.Large,
                ShowImage = true,
                LargeImage = LoadImage(imagePath32),
                Image = LoadImage(imagePath16),
                CommandHandler = command,
                Orientation = orientation,
                ToolTip = toolTipLine,
                Description = string.IsNullOrEmpty(text) ? "功能命令" : $"{text} 相关命令",
                HelpSource = new Uri(expandimgPath),
                // 交互效果
                IsEnabled = true,
                //ShowImage = true,
                // 尺寸样式
                Height = 6,  // 更合适的高度
                MinWidth = 20,
            };
        }

        /// <summary>
        /// 创建组合按钮（可重写）
        /// </summary>
        protected virtual void CreateComboButton(string imageName, string text, ICommand command,
            out RibbonCombo comboButton, Orientation orientation, string expandimgPath, string commandName, string title,
          string content, string expandcontent)
        {
            var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{imageName}32.png");
            var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{imageName}16.png");



            RibbonToolTip toolTipLine = new RibbonToolTip();//创建按钮提示
            toolTipLine.Command = commandName;//设置提示中显示的命令名
            toolTipLine.Title = title;//设置提示的标题
            toolTipLine.Content = content;//设置提示的内容
            //设置提示的附加内容
            toolTipLine.ExpandedContent = expandcontent;
            //设置在提示附加内容下显示的图像
            toolTipLine.ExpandedImage = File.Exists(expandimgPath) ? ImageHelper.FileToBitmap(expandimgPath) : GetDefaultImage(16);




            comboButton = new RibbonCombo()
            {
                ShowText = true,
                Text = text,
                Size = RibbonItemSize.Large,
                ShowImage = true,
                LargeImage = LoadImage(imagePath32),
                Image = LoadImage(imagePath16),
                CommandHandler = command,
                ToolTip = toolTipLine,
                Description = string.IsNullOrEmpty(text) ? "功能命令" : $"{text} 相关命令",
                HelpSource = new Uri(expandimgPath),
                // 交互效果
                IsEnabled = true,
               // ShowImage = true,
                // 尺寸样式
                Height = 6,  // 更合适的高度
                MinWidth = 20,
            };
        }

        /// <summary>
        /// 创建行按钮（可重写）
        /// </summary>
        protected virtual void CreateRowButton(string text, string imageName, ICommand command,
            out RibbonRowPanel rowPanel, Orientation orientation, string expandimgPath, string commandName, string title,
          string content, string expandcontent)
        {
            var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{imageName}32.png");
            var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{imageName}16.png");


            RibbonToolTip toolTipLine = new RibbonToolTip();//创建按钮提示
            toolTipLine.Command = commandName;//设置提示中显示的命令名
            toolTipLine.Title = title;//设置提示的标题
            toolTipLine.Content = content;//设置提示的内容
            //设置提示的附加内容
            toolTipLine.ExpandedContent = expandcontent;
            //设置在提示附加内容下显示的图像
            toolTipLine.ExpandedImage = File.Exists(expandimgPath) ? ImageHelper.FileToBitmap(expandimgPath) : GetDefaultImage(16);



            rowPanel = new RibbonRowPanel()
            {
                ShowText = true,
                Text = text,
                Size = RibbonItemSize.Large,
                ShowImage = true,
                LargeImage = LoadImage(imagePath32),
                Image = LoadImage(imagePath16),
                SubPanelResizeStyle = RibbonRowPanelResizeStyle.NoResize,
                Height = 40,
                ToolTip = toolTipLine,
                Description = string.IsNullOrEmpty(text) ? "功能命令" : $"{text} 相关命令",
                HelpSource = new Uri(expandimgPath),
                // 交互效果
                IsEnabled = true,
                //ShowImage = true,
                // 尺寸样式
                //Height = 6,  // 更合适的高度
                MinWidth = 20,
            };
        }

        /// <summary>
        /// 加载图片
        /// </summary>
        protected virtual System.Windows.Media.ImageSource LoadImage(string imagePath)
        {
            if (File.Exists(imagePath))
            {
                return ImageHelper.FileToBitmap(imagePath);
            }

            // 返回默认图片
            return GetDefaultImage(32);
        }

        /// <summary>
        /// 获取默认图片
        /// </summary>
        protected virtual System.Windows.Media.ImageSource GetDefaultImage(int size)
        {
            var visual = new System.Windows.Media.DrawingVisual();
            using (var context = visual.RenderOpen())
            {
                context.DrawRectangle(
                    System.Windows.Media.Brushes.LightGray,
                    new System.Windows.Media.Pen(System.Windows.Media.Brushes.DarkGray, 1),
                    new System.Windows.Rect(0, 0, size, size));
            }

            var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap(
                size, size, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
            bitmap.Render(visual);

            return bitmap;
        }

        /// <summary>
        /// 处理UI错误
        /// </summary>
        protected virtual void HandleUIError(System.Exception ex)
        {
            ($"UI创建错误: {ex.Message}").CadMessage2();
            ex.StackTrace?.CadAlert();
        }
    }































    /// <summary>
    /// CAD扩展应用程序的抽象基类
    /// </summary>
    public abstract class AppStartBase : IExtensionApplication
    {
        protected RibbonBuilderBase _ribbonBuilder;

        /// <summary>
        /// 初始化应用程序
        /// </summary>
        public virtual void Initialize()
        {
            try
            {
                "------------程序开始初始化------------".CadMessage2();

                // 加载依赖DLL
                LoadDependencies();

                RegisterService();
                ComponentManager.ItemInitialized += ComponentManager_ItemInitialized;

                AppDomain.CurrentDomain.AssemblyLoad += (sender, args) =>
                {

                    $"已加载程序集: {args.LoadedAssembly.FullName}".CadMessage2();

                    //RefreshRibbonDisplay();
                    // 切换到“默认”选项卡（主页）
                    //RibbonTabSwitcher.ActivateRibbonTab(RibbonTabSwitcher.BuiltInTabIds.Default);

                    //// 切换到“插入”选项卡
                    //RibbonTabSwitcher.ActivateRibbonTab(RibbonTabSwitcher.BuiltInTabIds.Insert);

                    //// 切换到“注释”选项卡
                    //RibbonTabSwitcher.ActivateRibbonTab(RibbonTabSwitcher.BuiltInTabIds.Annotate);
                };
            }
            catch (System.Exception ex)
            {
                HandleError("初始化失败", ex);
            }
            finally
            {
                "------------程序初始化完成------------".CadMessage2();
            }
        }

        private void ComponentManager_ItemInitialized(object sender, RibbonItemEventArgs e)
        {
            if (ComponentManager.Ribbon != null)
            {
                LoadUI();
                //等一会
                //Task.Delay(3000).ContinueWith(t => RefreshRibbonDisplay());
            }
            Autodesk.Windows.ComponentManager.ItemInitialized -= ComponentManager_ItemInitialized;
        }
        /// <summary>
        /// 移除已存在的Ribbon标签页
        /// </summary>
        private void RemoveExistingRibbon()
        {
            try
            {
                var ribbon = ComponentManager.Ribbon;
                if (ribbon != null)
                {
                    // 查找并移除自己的标签页
                    var tabsToRemove = ribbon.Tabs
                        .OfType<RibbonTab>()
                        .Where(t => t.Id.StartsWith("_TestTab") || t.Id.StartsWith("_CustomTab"))
                        .ToList();

                    foreach (var tab in tabsToRemove)
                    {
                        ribbon.Tabs.Remove(tab);
                    }
                }
            }
            catch (System.Exception ex)
            {
                $"移除旧Ribbon失败: {ex.Message}".CadMessage2();
            }
        }

        /// <summary>
        /// 刷新Ribbon显示
        /// </summary>
        private void RefreshRibbonDisplay()
        {
            try
            {
                // 强制刷新UI
                ComponentManager.Ribbon?.InvalidateVisual();
                if (ComponentManager.Ribbon is null)
                {
                    return;
                }
                // 激活第一个标签页（可选）
                if (ComponentManager.Ribbon?.Tabs.Count > 0)
                {
                    ComponentManager.Ribbon.Tabs[0].IsActive = true;
                }
                int index = (int)(ComponentManager.Ribbon?.Tabs.Count - 1);
                if (index >= 0)
                    ComponentManager.Ribbon.Tabs[index].IsActive = true;
            }
            catch (System.Exception ex)
            {
                $"刷新显示失败: {ex.Message}".CadMessage2();
            }
        }
        /// <summary>
        /// 加载UI界面（抽象方法，子类必须实现）
        /// </summary>
        protected abstract void LoadUI();

        /// <summary>
        /// 创建Ribbon构建器（可重写）
        /// </summary>
        protected virtual RibbonBuilderBase CreateRibbonBuilder()
        {
            return null;
        }

        /// <summary>
        /// 加载依赖项（可重写）
        /// </summary>
        protected virtual void LoadDependencies()
        {
            var dllPath = Path.Combine(ConfigPath.Dllfloder, "HandyControl.dll");
            if (!File.Exists(dllPath))
            {
                $"未加载到dll，没有找到文件 ---{dllPath} ---".CadMessage2();
                return;
            }

            Assembly.LoadFrom(dllPath);
            $"加载到dll ---{dllPath} ---".CadMessage2();
        }

        /// <summary>
        /// 错误处理（可重写）
        /// </summary>
        protected virtual void HandleError(string context, System.Exception ex)
        {
            Application.ShowAlertDialog(ex.Message);
            ex.Message.CadMessage2();
            ex.StackTrace?.CadMessage2();
            ("引发异常的方法:" + ex.TargetSite).CadMessage2();
            ("导致异常的应用程序或对象的名称:" + ex.Source).CadMessage2();
            ("导致当前异常的 Exception 实例:" + ex.InnerException).CadMessage2();
        }

        /// <summary>
        /// 注册服务（可重写）
        /// </summary>
        protected virtual void RegisterService()
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        }

        /// <summary>
        /// 程序集解析（可重写）
        /// </summary>
        protected virtual Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            try
            {
                AssemblyName assemblyName = new AssemblyName(args.Name);
                string[] possibleExtensions = new[] { ".dll", ".exe" };

                // 检查插件目录
                string pluginPath = Path.Combine(ConfigPath.AssemblyRunRootPath, "Plugins");
                foreach (var ext in possibleExtensions)
                {
                    string filePath = Path.Combine(pluginPath, $"{assemblyName.Name}{ext}");
                    if (File.Exists(filePath))
                    {
                        return Assembly.LoadFrom(filePath); 
                    }
                }

                // 检查主目录
                foreach (var ext in possibleExtensions)
                {
                    string filePath = Path.Combine(ConfigPath.AssemblyRunRootPath, $"{assemblyName.Name}{ext}");
                    if (File.Exists(filePath))
                    {
                        return Assembly.LoadFrom(filePath);
                    }
                }

                $"未能解析程序集: {args.Name}".CadMessage2();
            }
            catch (System.Exception ex)
            {
                $"程序集解析失败: {ex.Message}".CadMessage2();
            }
            finally
            {

            }
            return null;
        }

        public virtual void Terminate()
        {
            Debug.Print("------------程序结束运行------------");
        }
    }































    /// <summary>
    /// Ribbon选项卡刷新工具
    /// </summary>
    public static class RibbonRefreshHelper
    {
        /// <summary>
        /// 刷新Ribbon显示的正确方法
        /// </summary>
        public static void RefreshRibbon()
        {
            try
            {
                var ribbon = ComponentManager.Ribbon;
                if (ribbon != null)
                {
                    // 方法1：使用InvalidateVisual（WPF标准方法）
                    ribbon.InvalidateVisual();

                    // 方法2：更新布局
                    ribbon.UpdateLayout();

                    //// 方法3：刷新所有选项卡
                    //foreach (RibbonTab tab in ribbon.Tabs)
                    //{
                    //    tab.In();
                    //    tab.UpdateLayout();
                    //}
                }
            }
            catch (System.Exception ex)
            {
                $"刷新Ribbon失败: {ex.Message}".CadMessage2();
            }
        }

        /// <summary>
        /// 激活特定选项卡
        /// </summary>
        public static void ActivateTab(string tabId)
        {
            try
            {
                var ribbon = ComponentManager.Ribbon;
                if (ribbon != null)
                {
                    // 先取消激活所有选项卡
                    foreach (RibbonTab tab in ribbon.Tabs)
                    {
                        tab.IsActive = false;
                    }

                    // 激活目标选项卡
                    var targetTab = ribbon.Tabs.OfType<RibbonTab>()
                        .FirstOrDefault(t => t.Id == tabId);

                    if (targetTab != null)
                    {
                        targetTab.IsActive = true;
                        RefreshRibbon(); // 刷新显示
                    }
                }
            }
            catch (System.Exception ex)
            {
                $"激活选项卡失败: {ex.Message}".CadMessage2();
            }
        }
    }








    public static class RibbonTabSwitcher
    {
        /// <summary>
        /// 激活指定的Ribbon选项卡
        /// </summary>
        /// <param name="tabId">选项卡的ID（对于内置选项卡，通常是像"ID_TabHome"这样的字符串；对于自定义选项卡，是你创建时设置的Id）</param>
        /// <returns>是否成功激活</returns>
        public static bool ActivateRibbonTab(string tabId)
        {
            // 确保在UI线程上执行
            if (System.Windows.Application.Current?.Dispatcher.CheckAccess() == false)
            {
                return (bool)System.Windows.Application.Current.Dispatcher.Invoke(
                    new System.Func<string, bool>(ActivateRibbonTab), tabId);
            }

            var ribbon = ComponentManager.Ribbon;
            if (ribbon == null || ribbon.Tabs.Count == 0)
            {
                return false;
            }

            // 查找目标选项卡（不区分大小写）
            var targetTab = ribbon.Tabs.OfType<RibbonTab>()
                                  .FirstOrDefault(t => t.Id.Equals(tabId, System.StringComparison.OrdinalIgnoreCase));

            if (targetTab == null)
            {
                // 没找到选项卡
                return false;
            }

            // 取消激活所有选项卡
            foreach (RibbonTab tab in ribbon.Tabs)
            {
                tab.IsActive = false;
            }

            // 激活目标选项卡
            targetTab.IsActive = true;

            // 尝试调用Invalidate来刷新界面（如果可用）
            try
            {
               // ribbon.Invalidate(); // 这是AutoCAD RibbonControl的方法
            }
            catch
            {
                // 如果Invalidate方法不可用，可以忽略，因为激活选项卡通常足以触发UI更新
            }

            return true;
        }

        // 预定义的一些常见内置选项卡ID（请注意，这些ID可能因AutoCAD版本而异）
        public static class BuiltInTabIds
        {
            public const string Default = "ID_TabHome";      // 默认（主页）
            public const string Insert = "ID_TabInsert";     // 插入
            public const string Annotate = "ID_TabAnnotate"; // 注释
                                                             // 你可以根据实际需要添加更多内置选项卡的ID
        }
    }









}









